var GridSelectSelector = '.gridselect';
var GridSelectControl = Class.create(BaseControl, {
    drop:null,
    model:null,
    grid:null,

    loadView: function(element)
    {
        this.model = $(element);
        if (this.model.control) return;
        this.model.control = this;
        this.view = Builder.node('div', {className:'dropdown'},
            Builder.node('div', {className:'valuebox'})
        );
        this.model.value = this.model.getAttribute('value');
        var display = this.model.getAttribute('display');
        if (!display) display = this.model.value;
        this.setDisplayValue(display);
        if (this.model.hasClassName('filtered')) this.view.addClassName('filtered');
        this.model.insert({after:this.view}).hide();
        this.drop = new DropdownControl(this.view, this.model.getAttribute('drop'));
        this.drop.observe('show', this.observeGrid.bind(this));
    },

    observeGrid: function()
    {
        if (!this.grid)
        {
            var me = this;
            var grid = this.grid = this.drop.content.control;
            grid.onRowSelect = this.onRowSelect.bind(this);
            grid.onAjaxComplete = function(){
                grid.find('.clear_selection').each(function(e){
                    e.observe('click', me.clearSelection.bind(me));
                });
            };
        }
    },

    onRowSelect: function(memo)
    {
        this.setValue(memo.id);
        this.setDisplayValue(memo.display);
        this.drop.hide();
        this.fire('rowselect', memo);
    },

     clearSelection: function()
     {
        this.setValue('');
        this.setDisplayValue('');
        this.drop.hide();
        this.fire('rowselect', {id:'', display:''});
     },

    setValue: function(value)
    {
        if (Object.isUndefined(this.model.originValue)) this.model.originValue = this.model.value;

        this.model.value = value;
        if (value != this.model.originValue)
            this.view.addClassName('changed');
        else
            this.view.removeClassName('changed');
    },

    setDisplayValue: function(value)
    {
        this.view.down('.valuebox').update(value);
    }
});